package org.jeecg.modules.demo.DPT.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.modules.demo.DPT.entity.Ticket;
import org.jeecg.modules.demo.DPT.service.ITicketService;
import org.jeecg.modules.demo.DptAccount.entity.DptAccount;
import org.jeecg.modules.demo.DptAccount.service.IDptAccountService;
import org.jeecg.modules.demo.TicketDataString.entity.TicketDataString;
import org.jeecg.modules.demo.TicketDataString.service.ITicketDataStringService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 示例不带参定时任务
 * 
 * @Author Scott
 */
@Slf4j
public class SynDPTAccountJob implements Job {

	@Autowired
	SynTicketJob ticketJob;
	@Autowired
	IDptAccountService dptAccountService;
	@SneakyThrows
	@Override
	public void execute(JobExecutionContext jobExecutionContext) {
		List<DptAccount> list = dptAccountService.list();
		for (DptAccount dptAccount : list) {
			String account = dptAccount.getAccount();
			String pwd = dptAccount.getPwd();
					//token重新获取
					String token = getToken(account, pwd);
					dptAccount.setToken(token);
					dptAccountService.updateById(dptAccount);
		}

	}

	public String getToken(String account,String pwd){
		HttpClient client = HttpClient.newHttpClient();
		String params = "UserName=" +account+
				"&Password1=" +pwd;
		// 3. 构建 HttpRequest
		HttpRequest request = HttpRequest.newBuilder()
				.uri(URI.create("https://fp.xinpukeji.cn/wechatapi/NEWKP/LOGIN/GetToken2"))
				.header("Content-Type", "application/x-www-form-urlencoded") // 设置请求头
				.POST(HttpRequest.BodyPublishers.ofString(params))
				.build();

		// 4. 发送请求并获取响应
		HttpResponse<String> response = null;
		try {
			response = client.send(
					request,
					HttpResponse.BodyHandlers.ofString()
			);
			JSONObject rsp = JSONObject.parseObject(response.body());
			String id = rsp.getString("ID");
			return id;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


}
